import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginAPI, smsLoginAPI, registerAPI } from '@/api/user'
// import type { } from '@/api/user'
import type { LoginCredentials, LoginResponse } from '@/types/auth'
import type { UserInfo, UserRole } from '@/types/profile'
import { router } from '@/router'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  // const userInfo = ref<UserInfo | null>(null)

  // 用户信息
  interface UserInfo {
    id: number
    name: string
    phone: string
    avatar: string
    balance: number
    warehouseId?: string // 默认冷库ID
  }
  // 注册用户信息
  interface RegisterFormData {
    phone: string
    password: string
    operatorType: 'individual' | 'enterprise'
    operatorName: string
    idNumber: string
    smsCode: string
    idPhotos: File[]
  }

  // 初始化用户状态
  const initialize = () => {
    const token = localStorage.getItem('token')
    if (token) {
      fetchUserInfo()
      isLoggedIn.value = true
    }
  }

  // 用户登录
  const login = async (credentials: LoginCredentials) => {
    try {
      const response = await loginAPI(credentials)
      console.log(credentials, 'ggggggggggggggggggggggggg')
      console.log(response, 'hhhhhhhhhhhhhhhhhhhh')
      // 保存 token
      saveAuthData(response)

      // 获取用户信息
      await fetchUserInfo()

      return response
    } catch (error) {
      console.log('ffffffffffffffffff', error)
      throw new Error('登录失败: ' + (error as Error).message)
    }
  }

  // 短信登录
  const smsLogin = async (credentials: { phone: string; smsCode: string }) => {
    try {
      const response = await smsLoginAPI(credentials)

      // 保存 token
      saveAuthData(response)

      // 获取用户信息
      await fetchUserInfo()

      return response
    } catch (error) {
      throw new Error('短信登录失败: ' + (error as Error).message)
    }
  }

  // 发送短信验证码
  const sendSmsCode = async (phone: string) => {
    // try {
    //   await sendSmsCodeAPI(phone)
    //   return true
    // } catch (error) {
    //   throw new Error('发送验证码失败: ' + (error as Error).message)
    // }
  }

  // 用户注册
  const register = async (formData: FormData) => {
    try {
      // 模拟注册API
      await new Promise((resolve) => setTimeout(resolve, 0))

      // 实际项目中应调用注册API
      // await registerAPI(formData)
      const response = await registerAPI(formData)

      // 保存token等信息
      // saveAuthData(response)

      return response
    } catch (error) {
      if (error instanceof Error && error.message.includes('手机号')) {
        throw new Error('该手机号已注册')
      } else if (error instanceof Error && error.message.includes('验证码')) {
        throw new Error('验证码错误或已过期')
      } else {
        throw new Error('注册失败，请稍后重试')
      }
    }
  }
  // 保存认证数据
  const saveAuthData = (authData: LoginResponse) => {
    localStorage.setItem('token', authData.token)
    localStorage.setItem('refreshToken', authData.refreshToken)
    localStorage.setItem('tokenExpire', String(authData.tokenExpire))
    isLoggedIn.value = true
  }

  // 注销登录
  const logout = () => {
    // 清除所有用户数据
    userInfo.value = null
    isLoggedIn.value = false

    // 移除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('tokenExpire')

    // 跳转到登录页
    router.replace('/login')
  }

  // 用户信息
  const userInfo = ref<UserInfo>({
    id: 0,
    username: '',
    name: '',
    phone: '',
    avatar: '',
    balance: 0,
    role: 'guest',
    createTime: '',
    lastLoginTime: '',
  })

  // 加载状态
  const loading = ref(false)

  // 是否登录
  const isLoggedIn = computed(() => userInfo.value.id > 0)

  // 用户角色
  const userRole = computed(() => userInfo.value.role)

  // 是否是管理员
  const isAdmin = computed(
    () => userInfo.value.role === 'admin' || userInfo.value.role === 'manager',
  )

  // 获取用户信息
  const fetchUserInfo = async () => {
    loading.value = true
    try {
      // 模拟API调用获取用户数据
      userInfo.value = {
        id: 123456,
        username: 'cold_storage_user',
        name: '冷库管理员',
        phone: '13800138000',
        email: 'admin@coldstorage.com',
        avatar: '',
        balance: 3265.87,
        role: 'manager',
        warehouseId: 'WH-001',
        company: '冷链仓储服务有限公司',
        createTime: '2022-01-15',
        lastLoginTime: '2023-09-20 14:30:00',
      }
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateUserInfo = async (newInfo: Partial<UserInfo>) => {
    // 模拟API调用更新用户信息
    userInfo.value = { ...userInfo.value, ...newInfo }
  }

  // 更新头像
  const updateAvatar = async (avatarUrl: string) => {
    userInfo.value.avatar = avatarUrl
  }

  // 初始化用户状态
  initialize()

  return {
    userInfo,
    isLoggedIn,
    login,
    smsLogin,
    sendSmsCode,
    fetchUserInfo,
    logout,
    register,
    loading,
    userRole,
    isAdmin,
    updateUserInfo,
    updateAvatar,
  }
})
